import Vue from "vue";
import Vuex from "vuex";
import pinyin from "pinyin";

import login from "./modules/login";
import editDynamic from "./modules/editDynamic";
import newFriend from "./modules/newFriend";
import myInfo from "./modules/myInfo";
import createGroupChat from "./modules/createGroupChat";
import chat from "./modules/chat";
import addFriend from "./modules/addFriend";
import userInfo from "./modules/userInfo";
import socket from "@/socket";

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        user: "",
        friendList: [],
        lastMessageList: [],                // Message 页面信息列表, 里面还有 unread_count(未读信息数)
        topMessages: [],                    // 置顶的信息
        promptTone: "prompt-tone.mp3",      // 用哪个消息提示音
        groupChatList: [],                  // 群聊
        unreadGroupNotifications: false,    // 是否有未读群通知
    },
    getters: {
        friend_list(state, getters) {       // 生成依照昵称拼音排列的列表
            let { friendList } = state;
            let arr = Array.from({ length: 26 }, (x, i) => [String.fromCharCode(i + 65)]);

            friendList.forEach(item => {
                // 优先使用备注名进行排序
                const displayName = item.remark && item.remark.trim() !== '' ? item.remark : item.friendId.nickname;
                let arg = pinyin(displayName, { style: pinyin.STYLE_FIRST_LETTER }).flat().join("");
                arr[arg.toLocaleUpperCase().slice(0, 1).charCodeAt() - 65].push(item.friendId);
            })

            return arr;
        },      
        unReadMsgSum(state, getters) {      // 未读信息总数
            let num = 0;

            if (state.lastMessageList.length > 0) {
                state.lastMessageList.forEach(item => num += item.unread_count);
            }

            if (num) 
                return num;
            else 
                return "";
        },
    },
    mutations: {
        upUser(state, data) {                           // 用户登录添加用户信息
            state.user = data;
        },
        upNickname(state, data) {
            state.user.nickname = data;
        },
        upHeadImg(state, data) {
            state.user.headImgUrl = data;
        },
        upCover(state, data) {
            state.user.cover = data;
        },
        upFriend(state, data) {                         // 把从服务器中接收到的好友一个个 push 到 friendList 中
            data.forEach(element => state.friendList.push(element));
        },
        upLastMessages(state, message) {                // 改变最后消息
            let { lastMessageList, topMessages, friendList, groupChatList } = state;
            let { is_groupChat } = message;
            let index = -1, arr = [];

            if (!is_groupChat) {
                index = topMessages.findIndex(item => item.sender == message.sender);
                if (index == -1) index = topMessages.findIndex(item => item.sender == message.addresser);
                arr = topMessages;
            } else {
                index = topMessages.findIndex(item => item.addresser == message.addresser);
                arr = topMessages;
            }

            if (!is_groupChat && index == -1) {
                index = lastMessageList.findIndex(item => item.sender == message.sender);
                if (index == -1) index = lastMessageList.findIndex(item => item.sender == message.addresser);
                arr = lastMessageList;
            } else if (is_groupChat && index == -1) {
                index = lastMessageList.findIndex(item => item.addresser == message.addresser);
                arr = lastMessageList;
            }
            
            if (!is_groupChat) {
                // 查看联系人是否为置顶联系人，是就放到置顶消息
                (friendList.find(item => item.friendId._id == message.sender) || friendList.find(item => item.friendId._id == message.addresser)).is_top &&
                (arr = topMessages);
            } else {
                // 查看群聊是否为置顶群聊，是就放到置顶消息
                (groupChatList.find(item => item._id == message.addresser)?.is_top) && (arr = topMessages);
            }

            if (message?.unread_count == undefined && index === -1) {
                message = { ...message,  unread_count: 1 };
            } else {
                message = { ...message,  unread_count: arr[index].unread_count + 1 };
            }

            if (index === -1) {
                arr.unshift(message);
            } else {
                arr.splice(index, 1);
                arr.unshift(message);
            }
        },
        clearUnreadCount(state, data) {                   // 清空改对象的未读消息数
            let { lastMessageList, topMessages } = state;
            let [index, messageType] = data;

            if (messageType == 'topMessage') {
                topMessages[index].unread_count = 0;
            } else {
                lastMessageList[index].unread_count = 0;
            }
        },
        upMessageStatus(state, data) {                  // 这个方法是 MessageView 控制信息置顶、删除、标记未读用
            let { lastMessageList, topMessages, friendList, groupChatList } = state;
            let [index, operation, messageType] = data;
            let i = -1;

            // 找到该条消息在friendLis或者groupChatList的序号，标记置顶用的
            if (messageType == "topMessage") {
                if (topMessages[index].is_groupChat) {
                    i = groupChatList.findIndex(item => item._id == topMessages[index].addresser);
                } else {
                    i = friendList.findIndex(item => item.friendId._id == topMessages[index].sender);
                    if (i == -1) i = friendList.findIndex(item => item.friendId._id == topMessages[index].addresser);
                }
            } else {
                if (lastMessageList[index].is_groupChat) {
                    i = groupChatList.findIndex(item => item._id == lastMessageList[index].addresser);
                } else {
                    i = friendList.findIndex(item => item.friendId._id == lastMessageList[index].sender);
                    if (i == -1) i = friendList.findIndex(item => item.friendId._id == lastMessageList[index].addresser);
                }
            }

            switch (operation) {
                // 置顶该信息
                case "is_top":
                    topMessages.push({ ...lastMessageList[index], is_top: true });          // 添加 is_top 键，表示这个是否为置顶信息
                    if (!lastMessageList[index].is_groupChat) {
                        friendList.splice(i, 1, { ...friendList[i], is_top: true });        // 将该联系人标记为信息置顶联系人，方便下次再有消息还是置顶
                    } else {
                        groupChatList.splice(i, 1, { ...groupChatList[i], is_top: true });     // 将该群聊标记为信息置顶联系人，方便下次再有消息还是置顶
                    }
                    lastMessageList.splice(index, 1);                                       // 删除 lastMessageList 中该条信息
                    break;
                // 标记为未读
                case "markAsUnreadMsg":
                    if (messageType == "bottomMessage") {
                        lastMessageList.splice(index, 1, {
                            ...lastMessageList[index],
                            unread_count: 1, // 添加一个键，表示这个信息未读
                        });
                    } else if (messageType == "topMessage") {
                        topMessages.splice(index, 1, {
                            ...topMessages[index],
                            unread_count: 1, // 添加一个键，表示这个信息未读
                        });
                    }
                    break;
                // 删除该信息
                case "delMsg":
                    if (messageType == "bottomMessage") {
                        lastMessageList.splice(index, 1);
                    } else if (messageType == "topMessage") {
                        topMessages.splice(index, 1);
                    }
                    break;
                // 取消置顶
                case "noTopMsg":
                    topMessages[index].is_top = false;
                    lastMessageList.unshift(topMessages[index]);        // 将 is_top 改为 false 表示不是置顶信息
                    if (!topMessages[index].is_groupChat) {
                        friendList[i].is_top = false;                   // 将该联系人取消标记置顶
                    } else {
                        groupChatList[i].is_top = false;                // 将该群聊取消标记置顶
                    }
                    topMessages.splice(index, 1);                                   // 删除该条置顶消息
                    break;
            }
        },
        upMessage(state, message) {                     // 接受到系统中好友发送的信息就 push 到该好友的 message 数组
            let { friendList, groupChatList, user } = state;
            let { is_groupChat } = message;
            let arr;

            if (!is_groupChat) {
                if (message.sender == user._id)
                    arr = friendList.find(item => item.friendId._id == message.addresser);
                else
                    arr = friendList.find(item => item.friendId._id == message.sender);
            } else {
                arr = groupChatList.find(item => item._id == message.addresser)
            }

            // if (arr?.messages === undefined) {
            //     arr = { ...arr, messages: [] };
            // }

            arr.messages.push(message);
        },
        upGroupChats(state, groupChats) {
            state.groupChatList = groupChats;
        },
        updateUnreadGroupNotifications(state, hasUnread) {
            state.unreadGroupNotifications = hasUnread;
        },
    },
    actions: {
        modifyLike(context, data) {
            return new Promise((resolve, reject) => {
                socket.emit('modify_like', data, res => resolve(res));
            })
        },
    },
    modules: {
        login,
        editDynamic,
        newFriend,
        myInfo,
        createGroupChat,
        chat,
        addFriend,
        userInfo,
    },
});